package com.xing.binbackend.redis.spring;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xing.binbackend.redis.RedisStrategy;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class RedisTemplateStrategy<V> implements RedisStrategy<V> {
    private final RedisTemplate<String, String> redisTemplate;
    private final ObjectMapper objectMapper = new ObjectMapper();

    // 构造函数注入 RedisTemplate，确保 K 为 String 类型
    public RedisTemplateStrategy(RedisTemplate<String, String> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public void set(String key, V value) {
        set(key, value, 0); // 默认不过期
    }

    @Override
    public void set(String key, V value, long expireSeconds) {
        try {
            String json = objectMapper.writeValueAsString(value);
            redisTemplate.opsForValue().set(key, json, expireSeconds, TimeUnit.SECONDS);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("序列化对象失败", e);
        }
    }

    @Override
    public void multiSet(Map<String, V> keyValueMap) {
        for (Map.Entry<String, V> entry : keyValueMap.entrySet()) {
            set(entry.getKey(), entry.getValue());
        }
    }

    @Override
    public V get(String key, Class<V> clazz) {
        String json = redisTemplate.opsForValue().get(key);
        if (json == null) {
            return null;
        }
        try {
            // 使用泛型的实际类型进行反序列化
            return objectMapper.readValue(json, clazz);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("反序列化对象失败", e);
        }
    }
}